package com.kindnesslibrary.base;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.kindnesslibrary.R;
import com.kindnesslibrary.util.Contants;
import com.kindnesslibrary.util.MyUtil;
import com.kindnesslibrary.util.ToastUtil;

import java.io.File;
import java.util.concurrent.ExecutorService;

/**
 * Created by lenovo on 2017/5/29.
 * activity基类
 */
public abstract class BaseActivity extends AppCompatActivity {

    protected ExecutorService executorService; // 线程池
    protected Context mContext; // 当前上下文
    protected int statusBarHeight; // 状态栏高度
    protected int navigationBarHeight; // 虚拟按键高度
    private View view_status_bar; // 与状态栏同步高度的View
    private View view_bottom; // 虚拟键盘、键盘高度的View
    protected MyUtil myUtil = MyUtil.getInstance(); // 工具类
    protected DisplayMetrics mDisplayMetrics = new DisplayMetrics(); // 界面属性

    protected BaseHandler handler = new BaseHandler(this) {
        @Override
        protected void handleMessage(Context mContext, Message msg) {
            BaseActivity.this.handlerMessage(msg);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 去除标题栏
        mContext = this;
        super.onCreate(savedInstanceState);
        setContentView(initLayout());
        statusBarHeight = 0;
        navigationBarHeight = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
                && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            navigationBarHeight = myUtil
                    .getNavigationBarHeight(getApplicationContext());
            statusBarHeight = myUtil.getStatusBarHeight(getApplicationContext());
            // 透明状态栏
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            statusBarHeight = myUtil.getStatusBarHeight(getApplicationContext());
            navigationBarHeight = myUtil
                    .getNavigationBarHeight(getApplicationContext());
            // 透明状态栏
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            );
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }
        getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        view_status_bar = getStatusBarView();
        view_bottom = getBottomView();
        if (view_status_bar != null) {
            view_status_bar.setBackgroundColor(ContextCompat.getColor(getApplicationContext()
                    , BaseApplication.statusBarColor));
            ViewGroup.LayoutParams lp = view_status_bar.getLayoutParams();
            lp.height = statusBarHeight;
            view_status_bar.setLayoutParams(lp);
        }
        ViewTreeObserver vto = getWindow().getDecorView().getViewTreeObserver();
        vto.addOnGlobalLayoutListener(() -> {
            //应用可见区域，不包括状态栏
            Rect r = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
            //屏幕高度。不包括虚拟按键
            int screenHeight = getWindow().getDecorView().getRootView()
                    .getHeight();
            int bottom = 0;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                bottom = r.bottom + navigationBarHeight;
            } else {
                bottom = r.bottom;
            }
            int heightDifference = screenHeight - bottom;// r.top（状态栏）
            onKeyboardHeight(heightDifference);
        });
        initData(savedInstanceState); // 初始化数据
        initEvent(); // 初始化事件
    }

    /**
     * 向子类传递键盘高度
     *
     * @param height 0:键盘收起;<0:键盘弹出
     */
    protected void onKeyboardHeight(int height) {
        if (view_bottom != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                ViewGroup.LayoutParams lp = view_bottom.getLayoutParams();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    lp.height = height + navigationBarHeight;
                } else {
                    lp.height = height;
                }
                view_bottom.setLayoutParams(lp);
            }
        }
    }

    /**
     * 启动线程
     *
     * @param runnable
     */
    protected void startRunnable(Runnable runnable) {
        if (runnable == null) {
            ToastUtil.showToast("Send failed.");
            return;
        }
        if (executorService == null) {
            executorService = BaseApplication.getInstance().getExecutorService();
        }
        executorService.execute(runnable);
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
        addChildrenView();
    }

    /**
     * 在原来layout布局基础上添加布局
     */
    protected void addChildrenView() {
        int childrenView = getLayout();
        if (childrenView == 0) {
            return;
        }
        FrameLayout mContainLayout = (FrameLayout) findViewById(R.id.contain_layout);
        LayoutInflater.from(mContext).inflate(childrenView, mContainLayout, true);
    }

    protected <T extends View> T getView(int viewId) {
        return (T) findViewById(viewId);
    }

    protected int initLayout(){
        return R.layout.defalut_activity_layout;
    }

    /**
     * 启动系统相机并返回拍照图片存储地址
     *
     * @param requestCode
     * @return
     */
    protected File startCamera(int requestCode) {
        // 检查是否包含外部存储
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            // 检查是否包含照相机权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) !=
                    PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.CAMERA}, Contants.CAMERA_CODE);
                return null;
            }
            File file = new File(Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera");
            if (file == null) {
                ToastUtil.showToast(getString(R.string.device_no_support));
                return null;
            }
            if (!file.exists())
                file.mkdirs();
            file = new File(file.getPath()
                    + "/" + System.currentTimeMillis() + ".jpeg");
            Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            Uri fileUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                fileUri = FileProvider.getUriForFile(this, getPackageName(), file);
                in.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            } else {
                fileUri = Uri.fromFile(file);
            }
            in.putExtra(MediaStore.EXTRA_OUTPUT,
                    fileUri);
            startActivityForResult(in, requestCode);
            return file;
        } else {
            ToastUtil.showToast(getString(R.string.device_no_support));
        }
        return null;
    }

    /**
     * 跳转到裁剪图片
     *
     * @param requestCode
     * @param inFile      读取路径
     * @param outFile     裁剪后输出路径
     */
    protected void startPhotoZoom(int requestCode, File inFile, File outFile) {
        if (inFile == null && outFile == null) {
            ToastUtil.showToast(getString(R.string.picture_clipping_failed));
            return;
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        int width = getWindowManager().getDefaultDisplay().getWidth() / 2;
        intent.putExtra("outputX", width);
        intent.putExtra("outputY", width);
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        Uri inUri, outUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            inUri = FileProvider.getUriForFile(this, getPackageName(), inFile);
        } else {
            inUri = Uri.fromFile(inFile);
        }
        outUri = Uri.fromFile(outFile);
        intent.setDataAndType(inUri, "image/*");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Contants.CAMERA_CODE) {
            if (permissions.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                onCameraPermissionsResultOK();
            }
        }
    }

    /**
     * 相机申请权限成功
     */
    protected void onCameraPermissionsResultOK() {

    }

    /**
     * 获取状态栏的View
     *
     * @return
     */
    protected View getStatusBarView() {
        return findViewById(R.id.view_status_bar);
    }

    /**
     * 获取虚拟按键、键盘高度的View
     *
     * @return
     */
    protected View getBottomView() {
        return findViewById(R.id.view_navigation_bar);
    }

    protected abstract void handlerMessage(Message msg); // 处理handler消息

    protected abstract int getLayout(); // 初始化布局

    protected abstract void initData(Bundle savedInstanceState); // 初始化数据

    protected abstract void initEvent(); // 初始化事件

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 将之前处理的消息移除，以免内存泄漏
        handler.removeCallbacksAndMessages(null);
        handler = null;
        System.gc();
    }
}
